#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: LiangChao
@email：kevinleong1011@hotmail.com
@desc: 
"""
from makit import fn
from .context import default_context
from .log import logger
from .utils import parse_test_info

from .manage import mk


class TestStatus:

    def __init__(self, name=None, default=None, reset=None):
        self._name = name or self.__class__.__name__
        self._fullname = None
        self.changed_by = None
        self.changed = False
        self.default = default
        self.value = default
        self._reset = reset

    @property
    def name(self):
        if not self._fullname:
            _, fullname, _ = parse_test_info(self.instance.__class__)
            self._fullname = f'{self._name} of {fullname}'
        return self._fullname

    def __set__(self, instance, value):
        self.instance = instance
        self.changed = changed = value != self.default
        mk.info(f'Status {self.name} set to {value}', frame_depth=3)
        self.value = value
        caller = fn.get_caller_info()
        # project = mk.get_project(instance.__class__)
        test = mk.current_test()
        if test == f'{caller.module.__name__}.{caller.func}':
            pass  # 如果
        if changed:
            logger.debug(f'Status changed')
            self.changed_by = test
            if test:
                test.context.push_status(self)
            else:
                default_context.push_status(self)
        else:
            self.changed_by = None

    def __get__(self, instance, owner):
        self.instance = instance
        return self.value

    def reset(self, func):
        self._reset = func
        return func

    def recover(self, context):
        if self._reset:
            if isinstance(self._reset, str):
                self._reset = getattr(self.instance, self._reset)
            _, fullname, _ = parse_test_info(self.instance.__class__)
            mk.info(f'Recover status {self.name} to {self.default} by calling {fullname}.{self._reset.__name__}')
            self.value = self.default
            self.changed_by = None
            self.changed = False
            fn.run(self._reset, self.instance, **context.data)


class StatusBuilder:
    def __getattr__(self, item):
        self.name = item
        return self

    def __call__(self, default, reset=None):
        return TestStatus(self.name, default, reset)


status = StatusBuilder()
